<?php
/**
 * description:签到大转盘抽奖
 * Created by Jasmine.
 * Date: 2016/8/1
 * Address: 浙江宣逸网络科技有限公司
 */

namespace Common\Model;


class SignLuckyModel extends BaseModel{
    //大转盘抽奖结果
    const LUCKY_PRIZE_NULL          =0;//谢谢参与
    const LUCKY_PRIZE_FIRST         =1;//一等奖
    const LUCKY_PRIZE_SECOND        =2;//二等奖
    const LUCKY_PRIZE_THIRD         =3;//三等奖
    const LUCKY_PRIZE_FORTH         =4;//四等奖
    const LUCKY_PRIZE_FIFTH         =5;//五等奖

    //大转盘概率基数
    const LUCKY_RATE_SUM        = 100000;

    //签到奖励配置类型
    const PRIZE_TYPE_SIGN_CONTINUE       =1;//连续登录奖励
    const PRIZE_TYPE_SIGN_LUCKY          =2;//签到宝箱奖励
    const PRIZE_TYPE_DIAL_POINT          =3;//积分大转盘

    //大转盘抽奖奖品发货状态
    const PRIZE_ACCEPT_STATUS_DEFAULT    =1;//默认发货
    const PRIZE_ACCEPT_STATUS_DID        =2;//已发货
    const PRIZE_ACCEPT_STATUS_NO         =3;//未发货

    public static function getLuckyPrizeStatus(){
        return array(
            self::LUCKY_PRIZE_NULL=>'谢谢参与',
            self::LUCKY_PRIZE_FIRST=>'一等奖',
            self::LUCKY_PRIZE_SECOND=>'二等奖',
            self::LUCKY_PRIZE_THIRD	=>'三等奖',
            self::LUCKY_PRIZE_FORTH	=>'四等奖',
            self::LUCKY_PRIZE_FIFTH	=>'五等奖',
        );
    }

    public static function getPrizeAcceptStatus(){
        return array(
            self::PRIZE_ACCEPT_STATUS_DEFAULT   => '默认发货',
            self::PRIZE_ACCEPT_STATUS_DID       => '已发货',
            self::PRIZE_ACCEPT_STATUS_NO        => '未发货'
        );
    }

    /**
     * 读取大转盘配置
     * author:wwl
     * return array
     */
    public static function readLuckyPrizeSet($uid,$type=self::PRIZE_TYPE_SIGN_LUCKY){
        $luckyM = M('lucky_prize',null,DB_MAIN_CFG);
        $luckyLogM = M('u_lucky_log',null,DB_MAIN_CFG);

        $data = $luckyM->where("type={$type}")->select();

        //调整中奖率
        foreach($data as $key => $val){
            if(floatval($val['hitRate']) > 0){

                if($val['prizeNum'] == 0){//奖品剩余数量

                    $data[5]['hitRate'] += floatval($data[$key]['hitRate']);
                    $data[$key]['hitRate'] = 0;
                    $luckyM->where("id={$data[$key]['id']}")->setField('hitRate',$data[$key]['hitRate']);
                    $luckyM->where("id={$data[5]['id']}")->setField('hitRate',$data[5]['hitRate']);

                }else if($val['dayLimitTimes'] > 0){//日限制
                    $t = time();
                    $start = mktime(0,0,0,date("m",$t),date("d",$t),date("Y",$t));
                    $end = mktime(23,59,59,date("m",$t),date("d",$t),date("Y",$t));
                    $dayTimes = $luckyLogM->where("prizeID = {$val['id']} && uid={$uid} && addTime between {$start} and {$end}")->count();
                    if($dayTimes >= $val['dayLimitTimes']){
                        $data[5]['hitRate'] += floatval($data[$key]['hitRate']);
                        $data[$key]['hitRate'] = 0;
                    }
                } else if($val['allLimitTimes'] > 0){//总限制
                    $allTimes = $luckyLogM->where("prizeID = {$val['id']} && uid={$uid}")->count();
                    if($allTimes > $val['allLimitTimes']){
                        $data[5]['hitRate'] += floatval($data[$key]['hitRate']);
                        $data[$key]['hitRate'] = 0;
                    }
                }
//                else if($val['prizeType'] == 6){  //异业券库存
//
//                    $elcNum = M('elect_card_base_info',null,DB_MAIN_CFG)->where("id={$val['extra']}")->field('deliverNum,stock')->find();
//                    if($elcNum['deliverNum'] >= $elcNum['stock']){
//                        //异业券没有库存
//                        $data[5]['hitRate'] += floatval($data[$key]['hitRate']);
//                        $data[$key]['hitRate'] = 0;
//                    }
//                }

            }

        }
        return $data;
    }

    /**
     * 得到大转盘结果
     * @param uid
     * @param type:抽奖类型：2、签到大转盘抽奖。3、积分大转盘抽奖
     */
    public static function getLuckyResult($uid,$type=SignLuckyModel::PRIZE_TYPE_SIGN_LUCKY){
//        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

        $sum = self::LUCKY_RATE_SUM;
        $num = rand(1,$sum);

        $luckySet = self::readLuckyPrizeSet($uid,$type);

        $rank = array();$rate = array();
        foreach($luckySet as $key=>$val){
            $rank[] = $val['prizeRank'];
            $rate[] = $val['hitRate'];
        }
        //中奖概率 升序，中奖等第升序
        array_multisort($rate,SORT_ASC,$rank,SORT_ASC,$luckySet);
        $hitData = array();
        $minNum = intval(0); $maxNum = intval(0);
        foreach($luckySet as $key => $value){
            if($key>0){$minNum = $maxNum;}
            $maxNum += $value['hitRate']*$sum;
            if($num>$minNum && $num <= $maxNum){
                $hitData['prizeID'] = $value['id'];
                $hitData['prizeRank'] = $value['prizeRank'];
                $hitData['val'] = $value['extra'];
                $hitData['type'] = $value['type'];
                $hitData['prizeType'] = $value['prizeType'];
                if($value['prizeType'] == 6){//异业券
                    //获取异页券号 并更新异页券列表信息
                    $code = self::getCodeAndUpdate($uid,$value['extra']);
                    if($code['status']==1){
                        //卡券号获取失败，请联系管理员
                        $hitData['prizeNote'] = $value['prizeName']."<br/>券号：卡券号获取失败，请联系管理员";
                    } else{
                        $hitData['prizeNote'] = $value['prizeName']."<br/>券号：".$code['msg'];
                    }
                } else if($value['prizeType'] == 4){//卡券
                    $code = CouponModel::sendCard_both($value['extra'],$uid,OBJ_TYPE_LUCKY);
                    if($code['status']==1){
                        //卡券号获取失败，请联系管理员
                        $hitData['prizeNote'] = $value['prizeName']."<br/>券号：卡券号获取失败，请联系管理员";
                    } else{
                        $hitData['prizeNote'] = $value['prizeName']."<br/>券号：".$code['code'];
                    }
                } else{
                    $hitData['prizeNote'] = $value['prizeName'];
                }
            }
        }

        if(!$hitData){
            //抽奖结果为空集
            $dataFailure['msg'] = "抽奖失败，请重新抽奖";
            return $dataFailure;
        } else{
            //保存抽奖结果
            if($hitData['type'] == SignLuckyModel::PRIZE_TYPE_DIAL_POINT){
                //取基础消耗积分值
                $basePoint = M('cfg_config',null,DB_MAIN_CFG)->where("cfgName='POINT_LOTTERY_DIAL_BASE_POINT'")->getField('cfgValue');
            }
            $data = self::saveUserLuckyLog($uid,$hitData['prizeRank'],$hitData['prizeID'],$hitData['prizeNote'],$hitData['val'],$hitData['type'],$hitData['prizeType'],$basePoint);
            return $data;
        }
    }

    /**
     * 保存用户大转盘抽奖记录
     * author: wwl
     * @param $prizeRank 中奖等第
     * @param $id 奖品编号
     * @param $val 变化量
     * @param $type 活动类型:2、签到大转盘抽空。3、积分大转盘抽奖
     * @param $prizeType 奖品类型
     * @param $baseNum 针对积分大转盘，积分抽奖消耗积分值
     * Return array
     */
    public static function saveUserLuckyLog($uid,$prizeRank,$id,$prizeNote,$val,$type,$prizeType,$baseNum=0){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');
        if(!$uid){
            return $dataFailure;
        }
        $time = time();
        $uInfo = M('u_user_base',null,DB_MAIN_CFG)->where("uid={$uid}")->field('realName,bindPhone,province,city,district,address')->find();
        $data = array(
            'uid'       =>$uid,
            'realName'  =>$uInfo['realName'],
            'bindPhone' =>$uInfo['bindPhone'],
            'prizeID'   =>$id,
            'type'      =>$type,
            'prizeRank' =>$prizeRank,
            'prizeNote' =>$prizeNote,
            'addTime'   =>$time
        );
        if($prizeType == ELEMENT_TYPE_ENTITY){
            $data['status'] = self::PRIZE_ACCEPT_STATUS_NO;
        } else{
            $data['status'] = self::PRIZE_ACCEPT_STATUS_DEFAULT;
        }
        $addId = M('u_lucky_log',null,DB_MAIN_CFG)->add($data);
        if($addId){
            //操作类型
            if($type == SignLuckyModel::PRIZE_TYPE_SIGN_LUCKY){
                $operation = OPT_SIGN_LUCKY;
                //u_sign 已抽奖次数+1
                M('u_sign',null,DB_MAIN_CFG)->where("uid={$uid}")->setInc("usedTimes");
            } else $operation = OPT_POINT_LOTTERY;
            //积分抽奖 抽奖消耗积分和中奖积分加减
            if($prizeType == ELEMENT_TYPE_POINT){
                if($type == SignLuckyModel::PRIZE_TYPE_DIAL_POINT && $baseNum>0){
                    $changePoint = intval($val - $baseNum);
                    if($changePoint > 0){
                        UserModel::plusPoint($uid,-1,$changePoint,OPT_POINT_LOTTERY);
                    } else{
                        UserModel::minusPoint($uid,-1,abs($changePoint),OPT_POINT_LOTTERY);
                    }
                } else{
                    UserModel::plusPoint($uid,-1,$val,$operation);
                }
            } else{
                if($type == SignLuckyModel::PRIZE_TYPE_DIAL_POINT && $baseNum>0){
                    UserModel::minusPoint($uid,-1,$baseNum,OPT_POINT_LOTTERY);
                }
            }
            if($prizeType == ELEMENT_TYPE_EXP){
                UserModel::plusEXP($uid,$val,$operation);
            }
            if($prizeType == ELEMENT_TYPE_ENTITY){
                //抽中实物，判断用户收获地址是否填写完整
                if($uInfo['province'] && $uInfo['city'] && $uInfo['district'] && $uInfo['address']){
                    $dataSuccess['address'] = 0;
                } else{
                    $dataSuccess['address'] = 1;
                }
            }
            $dataSuccess['msg'] = $prizeRank;
            $dataSuccess['note'] = $prizeNote;
            $ids = M('lucky_prize',null,DB_MAIN_CFG)->where("type={$type}")->getField("id",true);
            if($ids){
                $angle=0;
                foreach($ids as $k=>$v){
                    if($id == $v){
                        $angle = $k+1;
                        break;
                    }
                }
                $dataSuccess['angle'] = $angle;
                self::adjustPrizeNum($id);
            }
            return $dataSuccess;
        } else {
            $dataFailure['msg'] = "抽奖失败，请联系管理员";
            return $dataFailure;
        }
    }

    //调整大转盘数量配置
    public static function adjustPrizeNum($id){
        $luckyM = M('lucky_prize',null,DB_MAIN_CFG);
        $prizeNum = $luckyM->where("id={$id}")->getField('prizeNum');
        if($prizeNum > 0) {
            $luckyM->where("id={$id}")->setDec("prizeNum");
        }
    }

    //取页面底图、转盘底图和活动规则
    public static function getBasePicAndRegulations($type=SignLuckyModel::PRIZE_TYPE_SIGN_LUCKY){
        $info['prizeInfo'] = M('lucky_prize',null,DB_MAIN_CFG)
            ->where("type=".$type." and prizeRank >= 0")
            ->field("prizeRank,prizePic")
            ->select();
        $data = M('cfg_config',null,DB_MAIN_CFG)->where('cfgName like "SIGN_DIAL_%"')->getField('cfgName,cfgValue',true);
        $info['pagePic'] = $data['SIGN_DIAL_PAGE_IMG'];
        $info['rule'] = explode('$',$data['SIGN_DIAL_RULE']);
        unset($info['rule'][count($info['rule'])-1]);
        return $info;
    }

    /**
     * 获取异页券号 并更新异页券列表信息
     * author: wwl
     * @param $uid 用户ID
     * @param $elcCardId 异页券编号
     * Return: code 异页券券号
     */
    public static function getCodeAndUpdate($uid,$elcCardId){
        $dataSuccess = array('status'=>self::SUCCESS,'msg'=>'成功');
        $dataFailure = array('status'=>self::FAILURE,'msg'=>'无效参数');

        if(!$uid || !$elcCardId){
            return $dataFailure;
        }
        $electM = M('elect_card_list',null,DB_MAIN_CFG);
        $elcInfo = $electM->where("uid=0 && elcCardId=$elcCardId")->field('id,code,password')->find();
        $data = array('uid'=>$uid,'deliverTime'=>time());
        $electM->where("id={$elcInfo['id']}")->setField($data);
        M('elect_card_base_info',null,DB_MAIN_CFG)->where("id={$elcCardId}")->setInc('deliverNum');

        if($elcInfo['password']){
            $code = $elcInfo['code'].",".$elcInfo['password'];
        } else{
            $code = $elcInfo['code'];
        }
        $dataSuccess['msg'] = $code;
        return $dataSuccess;
    }

    /**
     * 奖品说明
     * Author:wwl
     */
    public static function getLuckyPrizeNote($type=self::PRIZE_TYPE_SIGN_LUCKY){
        $luckySet = M('lucky_prize',null,DB_MAIN_CFG)
            ->where("type={$type} and prizeRank >0")
            ->field("prizeRank,prizeName,prizePic")
            ->select();
        $set = array();
        if($luckySet){
            $rank = array();
            foreach($luckySet as $val){
                $rank[] = $val['prizeRank'];
            }
            $rank = array_unique($rank);
            foreach($rank as $k=>$v){
                $set[$k]['prizeRank'] = $v;
                $set[$k]['prizeName'] = $luckySet[$k]['prizeName'];
                $set[$k]['prizePic'] = $luckySet[$k]['prizePic'];
            }
        }
        return $set;
    }

    /**
     * 奖品说明页底图
     * Author:wwl
     */
    public static function getPrizeBaseImg($type=2){
        $where = "cfgName='SIGN_DIAL_PRIZE_IMG'";
        if ($type == SignLuckyModel::PRIZE_TYPE_DIAL_POINT){
            $where = "cfgName='POINT_LOTTERY_DIAL_PRIZE_IMG'";
        }
        $baseImg = M('cfg_config',null,DB_MAIN_CFG)->where($where)->getField('cfgValue');
        return $baseImg;
    }

    /**
     * 计算签到余数
     * Author:wwl
     */
    public static function getCountDays($uid){
        $signAllTimes = M('u_sign',null,DB_MAIN_CFG)->where("uid={$uid}")->getField("signAllTimes");
        $day = 0;
        if($signAllTimes){
            $day = 7-($signAllTimes % 7);
        }
        return $day;
    }

    //签到统计
    public static function statistic(){
        $time = strtotime("-1 day");
        $start = mktime(0,0,0,date("m",$time),date("d",$time),date("Y",$time));
        $end = mktime(23,59,59,date("m",$time),date("d",$time),date("Y",$time));


        $showSignNum = M('u_sign',null,DB_MAIN_CFG)->where("todaySignTime between {$start} and {$end}")->max("todaySignRank");
        $realSignNum = M('u_sign_log',null,DB_MAIN_CFG)->where("addTime between {$start} and {$end}")->count();

        $data = array(
            'realSignNum'   => $realSignNum,
            'showSignNum'   => $showSignNum,
            'objDate'       => $time
        );
        M('u_sign_statistic',null,DB_MAIN_CFG)->add($data);
    }

}